package view;

import model.User;
import view.student.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 学生主界面
 */
public class StudentMainFrame extends JFrame {
    private User currentUser;
    private JPanel leftMenuPanel;
    private JPanel rightContentPanel;
    private CardLayout cardLayout;

    // 各个功能面板
    private ReservationRulesPanel reservationRulesPanel;
    private SeatReservationPanel seatReservationPanel;
    private MyReservationsPanel myReservationsPanel;
    private AttendancePanel attendancePanel;
    private StatisticsPanel statisticsPanel;
    private AIAssistantPanel aiAssistantPanel;
    private PersonalInfoPanel personalInfoPanel;

    // 菜单项
    private JPanel[] menuItems;
    private String[] menuTexts = { "预约规则", "座位预约", "我的预约", "考勤签到", "数据统计", "AI学习助手", "个人中心" };
    private String[] menuIcons = { "📋", "🎯", "📝", "⏰", "📊", "🤖", "👤" };
    private int selectedIndex = 0;

    public StudentMainFrame(User user) {
        this.currentUser = user;
        initComponents();
        setupLayout();
        setupEventListeners();
    }

    private void initComponents() {
        setTitle("自习室座位预约系统 - 学生端 (欢迎: " + currentUser.getName() + ")");
        setSize(1400, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化各个面板
        reservationRulesPanel = new ReservationRulesPanel();
        seatReservationPanel = new SeatReservationPanel(currentUser);
        myReservationsPanel = new MyReservationsPanel(currentUser);
        attendancePanel = new AttendancePanel(currentUser);
        statisticsPanel = new StatisticsPanel(currentUser, false); // false表示学生端
        aiAssistantPanel = new AIAssistantPanel();
        personalInfoPanel = new PersonalInfoPanel(currentUser);

        // 初始化菜单项数组
        menuItems = new JPanel[menuTexts.length];

        // 创建左侧菜单面板
        createLeftMenuPanel();

        // 创建右侧内容面板
        createRightContentPanel();
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 设置窗口背景色
        getContentPane().setBackground(new Color(248, 250, 252));

        // 现代化顶部工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        toolBar.setBackground(new Color(59, 130, 246)); // 现代化蓝色学生主题
        toolBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(37, 99, 235)));
        toolBar.setPreferredSize(new Dimension(1000, 60));

        JLabel welcomeLabel = new JLabel("欢迎，" + currentUser.getName());
        welcomeLabel.setForeground(Color.WHITE);
        welcomeLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));

        JButton logoutButton = new JButton("退出登录");
        styleModernButton(logoutButton, new Color(99, 102, 241));

        toolBar.add(welcomeLabel);
        toolBar.add(Box.createHorizontalStrut(20));
        toolBar.add(logoutButton);

        add(toolBar, BorderLayout.NORTH);
        add(leftMenuPanel, BorderLayout.WEST);
        add(rightContentPanel, BorderLayout.CENTER);

        // 退出登录事件
        logoutButton.addActionListener(_ -> {
            int option = JOptionPane.showConfirmDialog(this, "确定要退出登录吗?",
                    "确认", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                dispose();
                new LoginFrame().setVisible(true);
            }
        });
    }

    private void setupEventListeners() {
        // 菜单点击事件
        for (int i = 0; i < menuItems.length; i++) {
            final int index = i;
            menuItems[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    selectMenuItem(index);
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    if (index != selectedIndex) {
                        menuItems[index].setBackground(new Color(239, 246, 255));
                    }
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    if (index != selectedIndex) {
                        menuItems[index].setBackground(Color.WHITE);
                    }
                }
            });
        }

        // 默认选择第一个菜单项
        selectMenuItem(0);
    }

    /**
     * 创建左侧菜单面板
     */
    private void createLeftMenuPanel() {
        leftMenuPanel = new JPanel();
        leftMenuPanel.setLayout(new BoxLayout(leftMenuPanel, BoxLayout.Y_AXIS));

        // 渐变背景效果
        leftMenuPanel.setBackground(new Color(248, 250, 252));
        leftMenuPanel.setPreferredSize(new Dimension(220, 600));
        leftMenuPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 0, 1, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(10, 0, 10, 0)));

        // 菜单标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setPreferredSize(new Dimension(220, 80));
        titlePanel.setMaximumSize(new Dimension(220, 80));
        titlePanel.setBackground(new Color(248, 250, 252));
        titlePanel.setBorder(BorderFactory.createEmptyBorder(20, 15, 20, 15));

        JLabel menuTitle = new JLabel("功能菜单");
        menuTitle.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        menuTitle.setForeground(new Color(55, 65, 81));

        // 添加副标题
        JLabel subtitle = new JLabel("Student Portal");
        subtitle.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        subtitle.setForeground(new Color(156, 163, 175));

        titlePanel.add(menuTitle, BorderLayout.CENTER);
        titlePanel.add(subtitle, BorderLayout.SOUTH);
        leftMenuPanel.add(titlePanel);

        // 添加分隔线
        JPanel separator = new JPanel();
        separator.setPreferredSize(new Dimension(220, 1));
        separator.setMaximumSize(new Dimension(220, 1));
        separator.setBackground(new Color(229, 231, 235));
        leftMenuPanel.add(separator);

        // 添加一点空间
        leftMenuPanel.add(Box.createVerticalStrut(10));

        // 添加菜单项
        for (int i = 0; i < menuTexts.length; i++) {
            JPanel menuItem = createMenuItem(menuIcons[i], menuTexts[i]);
            menuItems[i] = menuItem;
            leftMenuPanel.add(menuItem);

            // 在菜单项之间添加小间距
            if (i < menuTexts.length - 1) {
                leftMenuPanel.add(Box.createVerticalStrut(5));
            }
        }

        // 添加弹性空间，将菜单项推向顶部
        leftMenuPanel.add(Box.createVerticalGlue());

        // 添加底部信息
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setPreferredSize(new Dimension(220, 40));
        bottomPanel.setMaximumSize(new Dimension(220, 40));
        bottomPanel.setBackground(new Color(248, 250, 252));
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));

        JLabel versionLabel = new JLabel("v1.0");
        versionLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
        versionLabel.setForeground(new Color(156, 163, 175));
        bottomPanel.add(versionLabel, BorderLayout.WEST);

        leftMenuPanel.add(bottomPanel);
    }

    /**
     * 创建单个菜单项
     */
    private JPanel createMenuItem(String icon, String text) {
        JPanel menuItem = new JPanel();
        menuItem.setLayout(new BorderLayout());
        menuItem.setPreferredSize(new Dimension(200, 50));
        menuItem.setMaximumSize(new Dimension(200, 50));
        menuItem.setBackground(Color.WHITE);
        menuItem.setOpaque(true);
        menuItem.setCursor(new Cursor(Cursor.HAND_CURSOR));
        menuItem.setBorder(BorderFactory.createEmptyBorder(8, 15, 8, 15));

        // 创建内容面板
        JPanel contentPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        contentPanel.setOpaque(false);

        // 图标面板 - 使用彩色图标替代emoji
        JPanel iconPanel = new JPanel();
        iconPanel.setPreferredSize(new Dimension(30, 30));
        iconPanel.setOpaque(false);

        // 根据图标类型创建不同的图标显示
        JLabel iconLabel = createIconLabel(icon, text);
        iconPanel.add(iconLabel);

        // 文本标签
        JLabel textLabel = new JLabel(text);
        textLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        textLabel.setForeground(new Color(75, 85, 99));
        textLabel.setBorder(BorderFactory.createEmptyBorder(0, 12, 0, 0));

        contentPanel.add(iconPanel);
        contentPanel.add(textLabel);

        menuItem.add(contentPanel, BorderLayout.WEST);

        // 添加圆角边框效果
        menuItem.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(2, 8, 2, 8),
                new RoundedBorder(8)));

        return menuItem;
    }

    /**
     * 创建图标标签
     */
    private JLabel createIconLabel(String icon, String text) {
        JLabel iconLabel = new JLabel();
        iconLabel.setHorizontalAlignment(SwingConstants.CENTER);
        iconLabel.setVerticalAlignment(SwingConstants.CENTER);
        iconLabel.setPreferredSize(new Dimension(24, 24));
        iconLabel.setOpaque(true);
        iconLabel.setBorder(new RoundedBorder(6));

        // 根据菜单类型设置不同的背景色和图标
        switch (text) {
            case "预约规则":
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(59, 130, 246));
                iconLabel.setText("📋");
                break;
            case "座位预约":
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(59, 130, 246));
                iconLabel.setText("🎯");
                break;
            case "我的预约":
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(34, 197, 94));
                iconLabel.setText("📝");
                break;
            case "数据统计":
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(245, 158, 11));
                iconLabel.setText("📊");
                break;
            case "AI学习助手":
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(147, 51, 234));
                iconLabel.setText("🤖");
                break;
            case "个人中心":
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(239, 68, 68));
                iconLabel.setText("👤");
                break;
            default:
                iconLabel.setBackground(Color.WHITE);
                iconLabel.setForeground(new Color(75, 85, 99));
                iconLabel.setText("●");
                break;
        }

        // 尝试使用支持emoji的字体
        try {
            iconLabel.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 14));
        } catch (Exception e) {
            iconLabel.setFont(new Font("Arial Unicode MS", Font.PLAIN, 14));
        }

        return iconLabel;
    }

    /**
     * 圆角边框类
     */
    private static class RoundedBorder implements javax.swing.border.Border {
        private int radius;

        public RoundedBorder(int radius) {
            this.radius = radius;
        }

        @Override
        public Insets getBorderInsets(Component c) {
            return new Insets(2, 2, 2, 2);
        }

        @Override
        public boolean isBorderOpaque() {
            return false;
        }

        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setColor(new Color(0, 0, 0, 0));
            g2d.fillRoundRect(x, y, width - 1, height - 1, radius, radius);
            g2d.dispose();
        }
    }

    /**
     * 创建右侧内容面板
     */
    private void createRightContentPanel() {
        cardLayout = new CardLayout();
        rightContentPanel = new JPanel(cardLayout);
        rightContentPanel.setBackground(new Color(248, 250, 252));

        // 添加各个面板到卡片布局
        rightContentPanel.add(reservationRulesPanel, "预约规则");
        rightContentPanel.add(seatReservationPanel, "座位预约");
        rightContentPanel.add(myReservationsPanel, "我的预约");
        rightContentPanel.add(attendancePanel, "考勤签到");
        rightContentPanel.add(statisticsPanel, "数据统计");
        rightContentPanel.add(aiAssistantPanel, "AI学习助手");
        rightContentPanel.add(personalInfoPanel, "个人中心");
    }

    /**
     * 选择菜单项
     */
    private void selectMenuItem(int index) {
        // 更新选中状态
        if (selectedIndex >= 0 && selectedIndex < menuItems.length) {
            updateMenuItemStyle(selectedIndex, false);
        }

        selectedIndex = index;
        updateMenuItemStyle(selectedIndex, true);

        // 切换到对应面板
        cardLayout.show(rightContentPanel, menuTexts[index]);

        // 刷新数据
        switch (index) {
            case 1: // 座位预约
                seatReservationPanel.refreshData();
                break;
            case 2: // 我的预约
                myReservationsPanel.refreshData();
                break;
            case 3: // 考勤签到
                // 考勤面板有自动刷新机制
                break;
            case 4: // 数据统计
                statisticsPanel.refreshData();
                break;
        }
    }

    /**
     * 更新菜单项样式
     */
    private void updateMenuItemStyle(int index, boolean selected) {
        if (index < 0 || index >= menuItems.length)
            return;

        JPanel menuItem = menuItems[index];

        if (selected) {
            menuItem.setBackground(new Color(59, 130, 246));
            updateMenuItemComponents(menuItem, Color.WHITE, new Color(255, 255, 255));
        } else {
            menuItem.setBackground(Color.WHITE);
            updateMenuItemComponents(menuItem, new Color(75, 85, 99), null);
        }

        menuItem.repaint();
    }

    /**
     * 递归更新菜单项组件颜色
     */
    private void updateMenuItemComponents(Container container, Color textColor, Color iconBgColor) {
        for (Component comp : container.getComponents()) {
            if (comp instanceof JLabel) {
                JLabel label = (JLabel) comp;
                // 如果是文本标签
                if (label.getText() != null && !isIconText(label.getText())) {
                    label.setForeground(textColor);
                }
                // 如果是图标标签，始终保持白色背景
                else if (isIconText(label.getText())) {
                    label.setBackground(Color.WHITE);
                }
            } else if (comp instanceof Container) {
                updateMenuItemComponents((Container) comp, textColor, iconBgColor);
            }
        }
    }

    /**
     * 判断是否为图标文本
     */
    private boolean isIconText(String text) {
        return text != null && (text.contains("📋") || text.contains("🎯") ||
                text.contains("📝") || text.contains("⏰") || text.contains("📊") ||
                text.contains("🤖") || text.contains("👤") ||
                text.equals("●"));
    }

    /**
     * 美化学生端按钮样式
     */
    /**
     * 现代化按钮样式（与统计页面一致）
     */
    private void styleModernButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(100, 38));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    private void styleStudentButton(JButton button) {
        button.setPreferredSize(new Dimension(100, 35));
        button.setBackground(new Color(255, 255, 255));
        button.setForeground(new Color(59, 130, 246));
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(255, 255, 255), 1),
                BorderFactory.createEmptyBorder(6, 14, 6, 14)));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(239, 246, 255));
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(255, 255, 255));
            }
        });
    }

}
